﻿using System;
using System.Net;
using System.Collections.Generic;
using FuelTracker.Models;
using System.IO;
using System.IO.IsolatedStorage;
using FuelTracker.Utils;
using System.Xml;
using System.Xml.Serialization;
using System.Linq;

namespace FuelTracker.DataAccess
{
    public class IsolatedStorageVehicleDao : IsolatedStorageDao, IVehicleDao
    {
        private const string DIRNAME = "VehicleStore";
        private const string FILE_VEHICLEINOFS = "VehicleInfos.xml";
        private const string FILE_LASTVEHICLE = "LastVehicle.xml";
        
        public IsolatedStorageVehicleDao() 
        {
            // Verzeichnis anlegen falls es noch nicht existiert
            IsolatedStorageUtils.CreateDirectory(isolatedStorage, DIRNAME);
        }

        public IEnumerable<VehicleInfo> LoadVehicleInfos()
        {
            string file = Path.Combine(DIRNAME, FILE_VEHICLEINOFS);

            if (!isolatedStorage.FileExists(file))
                return new List<VehicleInfo>();

            List<VehicleInfo> infos = Deserialize<List<VehicleInfo>>(file);

            return infos;
        }

        public void SaveVehicleInfos(IEnumerable<VehicleInfo> infos)
        {
            List<VehicleInfo> liste = infos.ToList();
            string file = Path.Combine(DIRNAME, FILE_VEHICLEINOFS);

            Deserialize<List<VehicleInfo>>(file);
        }

        public void SaveVehicle(Vehicle vehicle)
        {
            string file = Path.Combine(DIRNAME, vehicle.Id.ToString());

            Serialize(vehicle, file);
        }

        public Vehicle LoadVehicle(Guid id)
        {
            string file = Path.Combine(DIRNAME, id.ToString());

            Vehicle vehicle = Deserialize<Vehicle>(file);
            return vehicle;
        }

        public void SaveLastVehicleId(Guid id)
        {
            string file = Path.Combine(DIRNAME, FILE_LASTVEHICLE);

            Serialize(id, file);
        }

        public Guid LoadLastVehicleId()
        {
            string file = Path.Combine(DIRNAME, FILE_LASTVEHICLE);

            Guid id = Deserialize<Guid>(file);
            return id;
        }

    }
}
